#include "browser.h"
#include "ui_browser.h"

#include "customwebpage.h"

#include <QtCore>
#include <QtNetwork>
#include <QtGui>
#include <QtWebKit>

Browser::Browser(QWidget *parent) :
	QWidget(parent),
	ui(new Ui::Browser)
{
	ui->setupUi(this);

	progress = 0;
	ui->progressBar->setValue(0);
	firstTime = true;

	QFile file;
	file.setFileName(":/scripts/jquery.min.js");
	file.open(QIODevice::ReadOnly);
	jQuery = file.readAll();
	file.close();

	QNetworkProxyFactory::setUseSystemConfiguration(true);
	ui->view->setPage(new CustomWebPage(ui->view));

	connect(ui->btnBack, SIGNAL(clicked()), ui->view->pageAction(QWebPage::Back), SLOT(trigger()));
	connect(ui->btnForward, SIGNAL(clicked()), ui->view->pageAction(QWebPage::Forward), SLOT(trigger()));
	connect(ui->btnReload, SIGNAL(clicked()), ui->view->pageAction(QWebPage::Reload), SLOT(trigger()));
	connect(ui->btnStop, SIGNAL(clicked()), ui->view->pageAction(QWebPage::Stop), SLOT(trigger()));

	connect(ui->view, SIGNAL(loadFinished(bool)), SLOT(adjustLocation()));
	connect(ui->view, SIGNAL(titleChanged(QString)), SLOT(adjustTitle()));
	connect(ui->view, SIGNAL(loadProgress(int)), SLOT(setProgress(int)));
	connect(ui->view, SIGNAL(loadFinished(bool)), SLOT(finishLoading(bool)));
	ui->view->page()->setForwardUnsupportedContent(true);
	connect(ui->view->page(), SIGNAL(unsupportedContent(QNetworkReply*)), this, SLOT(unsupportedContent(QNetworkReply*)));

	ui->locationEdit->setSizePolicy(QSizePolicy::Expanding, ui->locationEdit->sizePolicy().verticalPolicy());
	connect(ui->locationEdit, SIGNAL(returnPressed()), SLOT(changeLocation()));

	load("http://scholar.google.ch/scholar_preferences?hl=en&as_sdt=0,5");
}

Browser::~Browser()
{
	delete ui;
}

void Browser::load(QString url)
{
	ui->view->load(url);
}

void Browser::slotFileDownloaded()
{
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(const_cast<QObject*>(sender()));

	QString ctype = reply->header(QNetworkRequest::ContentTypeHeader).toString();
	QStringList tokens = ctype.split(';');
	QString mime = (tokens.isEmpty() ? QString() : tokens.first()).trimmed().toLower();
	QString charset = (tokens.count() < 2 ? QString() : tokens.at(1)).trimmed();
	Q_UNUSED(charset);
	if (mime == "application/x-endnote-refer") {
		QString metadata = reply->readAll();
		QString citations = ui->view->page()->mainFrame()->evaluateJavaScript("window.clickedCitationsText;").toString();
		if (citations.toLower().startsWith("cited by ")) {
			citations = citations.mid(QString("cited by ").length());
			bool ok;
			int citCount = citations.toInt(&ok);
			if (ok) {
				metadata += QString("\n%Citations %1").arg(citCount);
			}
		}
		//qDebug() << citations;

		emit metadataDownloaded(metadata);
	} else if (mime == "application/pdf") {
		QByteArray contents = reply->readAll();
		emit pdfDownloaded(contents, reply->url().toString());
	} else {
		//TODO
		QTextEdit* textEdit = new QTextEdit(NULL);
		textEdit->setAttribute(Qt::WA_DeleteOnClose);
		textEdit->show();
		QString s;
		foreach (QByteArray h, reply->rawHeaderList()) {
			s += h + ": " + reply->rawHeader(h) + "\n";
		}
		textEdit->setPlainText(s);
	}
	reply->deleteLater();
}

void Browser::adjustLocation()
{
	ui->locationEdit->setText(ui->view->url().toString());
}

void Browser::changeLocation()
{
	QUrl url = QUrl(ui->locationEdit->text());
	ui->view->load(url);
	ui->view->setFocus();
}

void Browser::adjustTitle()
{
	emit titleChanged(ui->view->title());
}

void Browser::setProgress(int p)
{
	progress = p;
	ui->progressBar->setValue(p);
	adjustTitle();
}

void Browser::finishLoading(bool)
{
	progress = 100;
	ui->progressBar->setValue(100);
	adjustTitle();

	ui->view->page()->mainFrame()->evaluateJavaScript(jQuery);
	if (firstTime) {
		QFile file;
		file.setFileName(":/scripts/scholar-settings.js");
		file.open(QIODevice::ReadOnly);
		QString js = file.readAll();
		file.close();
		ui->view->page()->mainFrame()->evaluateJavaScript(js);
		firstTime = false;
	}
	{
		QFile file;
		file.setFileName(":/scripts/scholar-search-results.js");
		file.open(QIODevice::ReadOnly);
		QString js = file.readAll();
		file.close();
		ui->view->page()->mainFrame()->evaluateJavaScript(js);
	}
}

void Browser::unsupportedContent(QNetworkReply *reply)
{
	connect(reply, SIGNAL(finished()), this, SLOT(slotFileDownloaded()));

	QString ctype = reply->header(QNetworkRequest::ContentTypeHeader).toString();
	QStringList tokens = ctype.split(';');
	QString mime = (tokens.isEmpty() ? QString() : tokens.first()).trimmed().toLower();
	emit newDownloadStarting(reply, reply->url().toString(), mime);
}
